/*
 * AutoCompleteHandler.java
 *
 * Copyright(c) 2010
 * Michael Kroez
 * kroez@studiorutton.de
 *
 * All rights reserved.
 *
 * $Id$
 * 
 */

package de.studiorutton.gerengdic.indexeddictionary;

import android.os.Handler;
import android.os.Message;
import android.util.Log;
import de.studiorutton.gerengdic.databaseaccess.LanguageAccess.IndexPositionAccess.IndexAll;
import de.studiorutton.tre.AMatchResult;

public class AutoCompleteHandler extends Handler implements IAutoCompleteListener {
	private static final String TAG = "learningwords";
	
	private AutoCompleteAdapter aca;
	private IIndexedDictionaryView idl;
	
	private final static int NOTIFY_START = 0;
	private final static int NOTIFY_RECORD = 1;
	private final static int NOTIFY_ERROR = 2;
	private final static int NOTIFY_DONE = 3;
	private final static int NOTIFY_CANCELLED = 4;

	public AutoCompleteHandler( IIndexedDictionaryView idl, AutoCompleteAdapter aca) {
		super();
		this.aca = aca;
		this.idl = idl;
	}

	public void notifyStart() {
		Message msg = Message.obtain(this);
		msg.what = NOTIFY_START;
		sendMessage( msg );
	}
	
	public void newRecord(IndexAll ia, AMatchResult matchResult) {
		Message msg = Message.obtain( this );
		msg.what = NOTIFY_RECORD;
		AutoCompleteRecordContent acrc = new AutoCompleteRecordContent( matchResult.errors, ia, matchResult );
		msg.obj = acrc;
		sendMessage( msg );
		
	}

	public void notifyError(String string) {
		Message msg = Message.obtain( this );
		msg.what = NOTIFY_ERROR;
		msg.obj = string;
		sendMessage( msg );
	}

	public void notifyDone(int result) {
		Message msg = Message.obtain( this );
		msg.what = NOTIFY_DONE;
		sendMessage( msg );
	}
	
	public void handleMessage(Message msg) {
		switch (msg.what) {
		case NOTIFY_START:
//			Log.d( TAG, "AutoCompleteHandler: NOTIFY_START: clearing." );
			aca.clear( true );
			aca.notifyDataSetInvalidated();
			break;
		case NOTIFY_RECORD:
			AutoCompleteRecordContent acrc = (AutoCompleteRecordContent) msg.obj;
			aca.addItem( acrc );
			break;
		case NOTIFY_ERROR:
			String error = (String) msg.obj;
			idl.showErrorDialog(error);
			break;
		case NOTIFY_DONE:
			aca.sortItems();
			aca.notifyDataSetChanged();
		}
	}

}
